package com.googlecode.yami;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.plaf.basic.BasicButtonUI;

/**
 * Component to be used as tabComponent; Contains a JLabel to show the text and
 * a JButton to close the tab it belongs to
 */
public class TabHeaderComponent extends JPanel {
    /**
	 * 
	 */
    private static final long serialVersionUID = 1L;
    private final JTabbedPane pane;
    private ImageIcon closeIcon;
    private ImageIcon closeIconOn;

    TabHeaderComponent(final JTabbedPane pane) {
	// unset default FlowLayout' gaps
	super(new BorderLayout(20, 0));
	this.pane = pane;
	setOpaque(false);

	// make JLabel read titles from JTabbedPane
	JLabel label = new JLabel() {

	    public String getText() {
		int i = pane.indexOfTabComponent(TabHeaderComponent.this);
		if (i != -1) {
		    return pane.getTitleAt(i);
		}
		return null;
	    }
	};

	add(label, BorderLayout.WEST);
	label.setOpaque(false);
	// add more space between the label and the button
	label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
	// tab button
	// **********
	closeIcon = createImageIcon("images/close.png", "Close");
	closeIconOn = createImageIcon("images/closeOn.png", "Close");
	JButton button = new TabButton(closeIcon);
	button.setRolloverEnabled(true);
	button.setRolloverIcon(closeIconOn);
	// **********
	add(button);
	// add more space to the top of the component
	setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
    }

    protected ImageIcon createImageIcon(String path, String description) {
	java.net.URL imgURL = getClass().getResource(path);
	if (imgURL != null) {
	    return new ImageIcon(imgURL, description);
	} else {
	    System.err.println("Couldn't find file: " + path);
	    return null;
	}
    }

    class TabButton extends JButton implements ActionListener {

	public TabButton(ImageIcon icon) {
	    int size = 17;
	    this.setIcon(icon);
	    setPreferredSize(new Dimension(size, size));
	    setToolTipText("Close this tab");
	    // Make the button looks the same for all Laf's
	    setUI(new BasicButtonUI());
	    // Make it transparent
	    setContentAreaFilled(false);
	    // No need to be focusable
	    setFocusable(false);
	    setBorder(BorderFactory.createEtchedBorder());
	    setBorderPainted(false);
	    addActionListener(this);
	}

	public void actionPerformed(ActionEvent e) {
	    int i = pane.indexOfTabComponent(TabHeaderComponent.this);
	    if (i != -1) {
		// remove this pane
		pane.remove(i);
	    }
	}
    }
}
